package com.tamir.template.starter;

import com.tamir.template.bean.TNode;
import com.tamir.template.config.TemplateNodeTypeConfig;
import com.tamir.template.context.TemplateContext;
import com.tamir.template.express.handle.ITExpressValueHandle;

import java.util.List;

/**
 * @author : tanggh
 * @description :〈描述〉
 * @date : 2016/10/31
 */
public class TemplateStarter implements ITemplateStarter
{
    @Override
    public TNode parse(String templateText)
    {
        TNode rootNode = new TNode();
        TemplateNodeTypeConfig.getInstance().getILogicHandleParse
                (TemplateNodeTypeConfig
                .NODE_TYPE_LIST)
                .parse(rootNode, templateText);
        return rootNode;
    }

    @Override
    public String generateText(TNode node, TemplateContext context) throws Exception
    {
        StringBuffer textBuffer = new StringBuffer();
        if(node != null){
            List<TNode> subNodeList = node.getSubNodeList();
            if(subNodeList != null && !subNodeList.isEmpty()){
                ITExpressValueHandle handle = null;
                for (TNode subNode : subNodeList){
                    handle = TemplateNodeTypeConfig.getInstance().getITExpressValueHandle(subNode);
                    if(handle != null){
                        textBuffer.append(handle.generateText(subNode, context));
                    }
                }
            }
        }
        return textBuffer.toString();
    }

    @Override
    public Object getNodeValue(TNode node, TemplateContext context) throws Exception
    {
        if(node != null){

            ITExpressValueHandle handle  = TemplateNodeTypeConfig.getInstance().getITExpressValueHandle(node);
            return handle.getObject(node, context);
        }
        return null;
    }

}
